package org.luckyjourney.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.luckyjourney.config.QiNiuConfig;
import org.luckyjourney.entity.Comment;
import org.luckyjourney.entity.CommentVo;
import org.luckyjourney.entity.File;
import org.luckyjourney.entity.user.Favorites;
import org.luckyjourney.entity.user.Follow;
import org.luckyjourney.entity.user.User;
import org.luckyjourney.entity.user.dto.UserDTO;
import org.luckyjourney.entity.vo.*;
import org.luckyjourney.holder.UserHolder;
import org.luckyjourney.mapper.user.UserMapper;
import org.luckyjourney.service.CommentService;
import org.luckyjourney.service.FileService;
import org.luckyjourney.service.user.FavoritesService;
import org.luckyjourney.service.user.UserService;
import org.luckyjourney.util.AddressUtils;
import org.luckyjourney.util.BaseContext;
import org.luckyjourney.util.IPUtils;
import org.luckyjourney.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Stream;

/**
 * @description:
 * @Author: Xhy
 * @CreateTime: 2023-10-25 15:27
 */
@RestController
@RequestMapping("/luckyjourney/customer")
@Api(tags = "获取主页数据")
@Slf4j
public class CustomerController {


    @Autowired
    QiNiuConfig qiNiuConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private FileService fileService;
    @Autowired
    private FavoritesService favoritesService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserMapper userMapper;

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault());


    /**
     * 获取个人信息
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping("/getInfo/{userId}")
    @ApiOperation("获取个人信息")
    public R getInfo(@PathVariable Long userId) {
        return R.ok().data(userService.getInfo(userId));
    }


    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/getInfo")
    @ApiOperation("获取用户信息")
    public R getDefaultInfo() {
        return R.ok().data(userService.getInfo(UserHolder.get()));
    }

    /**
     * 获取关注人员
     *
     * @param basePage
     * @param
     * @return
     */
    @GetMapping("/follows")
    @ApiOperation("获取关注人员")
    public R getFollows(BasePage basePage) {
        Long userId = BaseContext.getCurrentId();

        return R.ok().data(userService.getFollows(userId, basePage));
    }

    /**
     * 获取粉丝
     *
     * @param basePage
     * @param
     * @return
     */
    @GetMapping("/fans")
    @ApiOperation("获取自己的粉丝")
    public R getFans(BasePage basePage) {
        Long userId = BaseContext.getCurrentId();

        //传入自己的id
        return R.ok().data(userService.getFans(userId, basePage));
    }


    /**
     * 获取所有的收藏夹
     *
     * @return
     */
    @GetMapping("/favorites")
    @ApiOperation("获取所有的收藏夹")
    public R listFavorites() {
        final Long userId = UserHolder.get();
        List<Favorites> favorites = favoritesService.listByUserId(userId);
        return R.ok().data(favorites);
    }


    /**
     * 获取指定收藏夹
     *
     * @param id
     * @return
     */
    @GetMapping("/favorites/{id}")
    @ApiOperation("获取指定收藏夹")
    public R getFavorites(@PathVariable Long id) {
        return R.ok().data(favoritesService.getById(id));
    }

    /**
     * 添加/修改收藏夹
     *
     * @param favorites
     * @return
     */
    @PostMapping("/favorites")
    @ApiOperation("添加/修改收藏夹")
    public R saveOrUpdateFavorites(@RequestBody @Validated Favorites favorites) {
        final Long userId = UserHolder.get();
        final Long id = favorites.getId();
        favorites.setUserId(userId);
        final int count = favoritesService.count(new LambdaQueryWrapper<Favorites>()
                .eq(Favorites::getName, favorites.getName()).eq(Favorites::getUserId, userId).ne(Favorites::getId, favorites.getId()));
        if (count == 1) {
            return R.error().message("已存在相同名称的收藏夹");
        }
        favoritesService.saveOrUpdate(favorites);
        return R.ok().message(id != null ? "修改成功" : "添加成功");
    }

    /**
     * 删除收藏夹
     *
     * @param id
     * @return
     */
    @DeleteMapping("/favorites/{id}")
    @ApiOperation("添加/删除收藏夹")
    public R deleteFavorites(@PathVariable Long id) {
        favoritesService.remove(id, UserHolder.get());
        return R.ok().message("删除成功");
    }


    /**
     * 订阅分类
     */
    @PostMapping("/subscribe")
    @ApiOperation("订阅分类")
    public R subscribe(@RequestParam(required = false) String types) {
        final HashSet<Long> typeSet = new HashSet<>();
        String msg = "取消订阅";
        if (!ObjectUtils.isEmpty(types)) {
            for (String s : types.split(",")) {
                typeSet.add(Long.parseLong(s));
            }
            msg = "订阅成功";
        }
        userService.subscribe(typeSet);
        return R.ok().message(msg);
    }

    /**
     * 获取用户订阅的分类
     *
     * @return
     */
    @GetMapping("/subscribe")
    @ApiOperation("获取用户订阅的分类")
    public R listSubscribeType() {
        return R.ok().data(userService.listSubscribeType(UserHolder.get()));
    }

    // 获取用户没订阅的分类
    @GetMapping("/noSubscribe")
    public R listNoSubscribeType() {
        return R.ok().data(userService.listNoSubscribeType(UserHolder.get()));
    }

    /**
     * 关注/取关
     *
     * @param
     * @return
     */
    @PostMapping("/followsModul")
    @ApiOperation("关注/取关")
    public R follows(@RequestBody Follow follow) {

        return R.ok().message(userService.follows(follow) ? "已关注" : "已取关");
    }

    /**
     * 用户停留时长修改模型
     *
     * @param model
     * @return
     */
    @PostMapping("/updateUserModel")
    @ApiOperation("用户停留时长修改模型")
    public R updateUserModel(@RequestBody Model model) {
        final Double score = model.getScore();
        if (score == -0.5 || score == 1.0) {
            final UserModel userModel = new UserModel();
            userModel.setUserId(UserHolder.get());
            userModel.setModels(Collections.singletonList(model));
            userService.updateUserModel(userModel);
        }
        return R.ok();
    }

    /**
     * 获取用户上传头像的token
     *
     * @return
     */
    @GetMapping("/avatar/token")
    @ApiOperation("获取用户上传头像的token")
    public R avatarToken() {
        return R.ok().data(qiNiuConfig.imageUploadToken());
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @PutMapping
    @ApiOperation("修改用户信息")
    public R updateUser(@RequestBody @Validated UpdateUserVO user) throws Exception {
        /*if (StringUtils.isEmpty(user.getSex())){
            return R.error().message("性别不能为空");
        }*/
        try {
            userService.updateUser(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.ok().message("修改成功");
    }

    /**
     * 新增评论
     *
     * @param comment
     * @return
     */
    @PostMapping("/addComment")
    @ApiOperation("新增评论")
    public R addComment(@RequestBody Comment comment, HttpServletRequest request) {
        if (StringUtils.isEmpty(comment.getNickName()) && StringUtils.isEmpty(comment.getVideoId())&& StringUtils.isEmpty(comment.getContent())) {
            return R.error().message("昵称.视频id和内容必须填写");
        }
        try {
            Long user = UserHolder.get();
            String  users= "b"+user;
            comment.setUserId(users);
            comment.setCreateTime(new Date());
//            String ipAddress = request.getRemoteAddr();
            String ipAddr = IPUtils.getIpAddr(request);
            String realAddress1 = AddressUtils.getRealAddress(ipAddr);
            comment.setIpAddress(realAddress1);
            commentService.saveOrUpdate(comment);
            // 日志记录
            log.info("评论添加成功: {}", comment);
            return R.ok().message("新增评论成功");
        } catch (Exception e) {
            // 异常处理
            log.error("评论添加失败: ", e);
            return R.ok().message("评论添加失败");
        }

    }

    /**
     * 获取评论
     * @param
     * @return
     */
    @PostMapping("/listComment/{videoId}")
    @ApiOperation("获取评论")
    public R listComment(@PathVariable Long videoId) {
        List<Comment> commentList = commentService.pageComment(videoId);
        commentList.forEach(comment -> {
            List<Comment> children = comment.getChildren();
            children.forEach(child -> {
                if(!StringUtils.isEmpty(child.getAvatar())){
                    Long avatar = Long.valueOf(child.getAvatar());
                    File fileTrustUrl = fileService.getFileTrustUrl(avatar);
                    if (!ObjectUtils.isEmpty(fileTrustUrl)){
                        child.setAvatar(fileTrustUrl.getFileKey());
                    }
                }
            });
            if(!StringUtils.isEmpty(comment.getAvatar())){
                Long avatar = Long.valueOf(comment.getAvatar());
                File fileTrustUrl = fileService.getFileTrustUrl(avatar);
                if (!ObjectUtils.isEmpty(fileTrustUrl)){
                    comment.setAvatar(fileTrustUrl.getFileKey());
                }
            }
        });
        return R.ok().data(commentList);
    }

    @PostMapping("/deleteComment")
    @ApiOperation("删除评论")
    public R deleteComment(@RequestBody CommentVo commentVo){
        Long user_id = UserHolder.get();
        //判断是不是作者本人
        if (user_id.equals(commentVo.getUserId())){
            commentService.remove(commentVo.getId());
        }else {
            //判断是不是自己的评论
            Comment comment = commentService.getById(commentVo.getId());
            if (!ObjectUtils.isEmpty(comment)){
                if (comment.getUserId().substring(1).equals("b")){
                    LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(User::getId,comment.getUserId().substring(1));
                    List<User> users = userMapper.selectList(wrapper1);
                    if (users.size()>0){
                        //yes
                        commentService.remove(commentVo.getId());
                    }else {
                        //no
                        return R.error().message("不能删除别人的评论");
                    }
                }

            }
        }
        return R.ok().message("删除成功");
    }





}
